#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include "Log.hpp"
#include "Init.hpp"

extern Log lg;

Init init;
class Task
{
public:
    Task() {}
    Task(int sockfd, const std::string &clientip, const uint16_t &port) : _sockfd(sockfd), _clientip(clientip), _clientport(port)
    {
    }
    void Excute()
    {
        // while (true)
        //{
        char inbuffer[4096];

        bzero(inbuffer, sizeof(inbuffer));
        ssize_t n = read(_sockfd, inbuffer, sizeof(inbuffer));
        if (n > 0)
        {
            inbuffer[n] = 0;
            // std::cout << "client say# " << inbuffer << std::endl;
            // std::string echo_string = "tcpserver echo# ";
            //echo_string += inbuffer;

            std::cout << "client key# " << inbuffer << std::endl;
            std::string echo_string = init.translation(inbuffer);

            write(_sockfd, echo_string.c_str(), echo_string.size());
        }
        else if (n == 0)
        {
            lg(Info, "%s:%d quit, server close sockfd: %d", _clientip.c_str(), _clientport, _sockfd);
        }
        else
        {
            lg(Warning, "read error, sockfd: %d, client ip: %s, client port: %d", _sockfd, _clientip.c_str(), _clientport);
        }
        //}
        close(_sockfd);
    }

    void operator()()
    {
        Excute();
    }

private:
    int _sockfd;
    std::string _clientip;
    uint16_t _clientport;
};